package cn.mesmile.flow.modules.processinstance.controller;

import cn.mesmile.flow.modules.processinstance.model.dto.StartProcessInstanceDTO;
import cn.mesmile.flow.modules.processinstance.model.vo.StartProcessInstanceVO;
import cn.mesmile.flow.modules.processinstance.service.ProcessInstanceService;
import lombok.AllArgsConstructor;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.*;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.task.api.Task;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zb
 * @date 2020/12/7 14:11
 * @Description
 */
@AllArgsConstructor
@RequestMapping("/api/v1/instance")
@RestController
public class ProcessInstanceController {

    private final ProcessInstanceService processInstanceService;

    private final RuntimeService runtimeService;

    private final TaskService taskService;

    private final RepositoryService repositoryService;

    private final ProcessEngine processEngine;

    @PostMapping("/start")
    public StartProcessInstanceVO start(@RequestBody StartProcessInstanceDTO startProcessInstanceDTO) {

        processInstanceService.start(startProcessInstanceDTO);

        return null;
    }


    @GetMapping("/get")
    public String get() {
        processInstanceService.get();
        return "success";
    }

    /**
     * 生成流程图
     *
     * @param processInstanceId 任务ID
     */
    @GetMapping(value = "/processDiagram/{processInstanceId}")
    public void genProcessDiagram(HttpServletResponse httpServletResponse,@PathVariable("processInstanceId") String processInstanceId) throws Exception {

        ProcessInstance pi = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId).singleResult();

        //流程走完的不显示图
        if (pi == null) {
            return;
        }
        Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();

        //使用流程实例ID，查询正在执行的执行对象表，返回流程实例对象
        String InstanceId = task.getProcessInstanceId();
        List<Execution> executions = runtimeService
                .createExecutionQuery()
                .processInstanceId(InstanceId)
                .list();

        //得到正在执行的Activity的Id
        List<String> activityIds = new ArrayList<>();
        List<String> flows = new ArrayList<>();
        for (Execution exe : executions) {
            List<String> ids = runtimeService.getActiveActivityIds(exe.getId());
            activityIds.addAll(ids);
        }

        //获取流程图
        BpmnModel bpmnModel = repositoryService.getBpmnModel(pi.getProcessDefinitionId());
        ProcessEngineConfiguration engconf = processEngine.getProcessEngineConfiguration();
        ProcessDiagramGenerator diagramGenerator = engconf.getProcessDiagramGenerator();
        InputStream in = diagramGenerator.generateDiagram(bpmnModel, "png", activityIds,
                flows,
               "宋体",
                "宋体",
                "宋体",
                engconf.getClassLoader(),
                1.0,true);
        OutputStream out = null;
        byte[] buf = new byte[1024];
        int legth = 0;
        try {
            out = httpServletResponse.getOutputStream();
            while ((legth = in.read(buf)) != -1) {
                out.write(buf, 0, legth);
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }



}
